#!/usr/bin/python3
# coding=utf-8
import sys
import json
import random

def iosdiagJoinData(raw):
    if raw.startswith('fail'):
        print({"status": "fail"})
        return

    disks = []
    stat = {}
    stat["disks"] = {"data": []}
    for s in raw.split('\n'):
        try:
            obj = json.loads(s)
        except Exception:
            continue
        dataSource = "singleIO_"
        if "percent" in str(obj):
            disks = [s['diskname'] for s in obj['summary'] \
                if s['diskname'] not in disks]
            stat["disks"]["data"] = \
                [{'key':disks.index(d), 'value':d} for d in disks]
            dataSource = "iohangOverview_"
        for d in disks:
            if (dataSource+d) not in stat.keys():
                stat[dataSource+d] = {"data": []}
            for s in obj['summary']:
                if d in s['diskname']:
                    if "percent" not in str(obj):
                        s["hung ios"] = \
                            sorted(s["hung ios"],\
                                key=lambda e:float(e['abnormal'].split()[-2]),\
                                reverse=True)[:10]
                    stat[dataSource+d]["data"] = s["hung ios"]

    s = json.dumps(stat, indent=4)
    print(s)

def extract_params():
    path, res, task_id = sys.argv[1], "", sys.argv[2]
    with open(path, 'r') as tmp:
        res = tmp.read()
    return res, task_id

if __name__ == "__main__":
    res, _ = extract_params()
    iosdiagJoinData(res)
